package com.itboye.hutouben.activity.store;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.itboye.hutouben.R;
import com.itboye.hutouben.activity.addressmanage.AddressListActivity;
import com.itboye.hutouben.activity.mysetting.SettingActivity;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.bean.GoPayBean;
import com.itboye.hutouben.bean.GouWuCheBean;
import com.itboye.hutouben.bean.MoneyShengyuBean;
import com.itboye.hutouben.bean.MyAddressBean;
import com.itboye.hutouben.presenter.DingDanPresenter;
import com.itboye.hutouben.presenter.SystemMessgeAPresenter;
import com.itboye.hutouben.presenter.UserPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.MathUtil;
import com.itboye.hutouben.util.MyGongJv;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.util.UIAlertView02;
import com.itboye.hutouben.volley.ResultEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.hutouben.activity.store.GoPayActivity.GOUWUINEXIT;
import static com.itboye.hutouben.util.MathUtil.sub;
import static java.lang.Double.parseDouble;

/**
 * 提交订单
 */
public class CommitOrderActivity extends BaseActivity implements Observer{
    TextView add_shap_title_tv;
    ImageView close_icon;
    TextView quzhifu, txt_zongji;
    RelativeLayout choose_address;
    TextView txt_zongji_money;//运费，总计，待支付,总金额
    ArrayList<GouWuCheBean> list = new ArrayList<>();
    LinearLayout goods_container;

    TextView address_people,address_phone,address_detail;
    MyAddressBean bean;
    UserPresenter userPresenter;
    DingDanPresenter dingDanPresenter;
    String uid;
    String moneys;
    String adressId="";//收货地址id
    StringBuffer sb=new StringBuffer();//保存购物车Id
    StringBuffer sb01=new StringBuffer();//保存数量
    StringBuffer sb02=new StringBuffer();//保存规格
    String gwcId="";

    public static String GOUWUSHUXIN= "gouwu.shuxin";// 生成订单后  刷新购物车

    TextView order_jifen,order_jian,order_jia;
    EditText order_num;
    SystemMessgeAPresenter presenter;

    MoneyShengyuBean yeBean;
    double zongMoney;//总价
    String score;//积分
    String score_rate;//积分比例

    private UIAlertView02 uiAlertView;

    RelativeLayout order_type,order_taitou,order_shuihao;//选择发票类型，发票抬头，添加税号
    TextView tv_type;//发票类型
    EditText et_taitou,et_shuihao;//抬头，税号
    private OptionsPickerView pvOptions;

    String type="";//发票类型(1=>个人,2=>企业)[可选],int
    String taitou;//发票抬头
    String shuihao;//发票税号
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commit_order);
        add_shap_title_tv.setText(getString(R.string.commitorder));
        uid= SPUtils.get(this,null, Const.ID,"")+"";
        getOptionData();
        initOptionPicker();
        userPresenter=new UserPresenter(this);
        dingDanPresenter=new DingDanPresenter(this);
        presenter=new SystemMessgeAPresenter(this);
        showProgressDialog("获取地址中,请稍后", true);
        userPresenter.queryAddress(IsUtilUid.sId(), uid);
        yeBean = new MoneyShengyuBean();
        list = (ArrayList<GouWuCheBean>) getIntent().getSerializableExtra("list");
        moneys=getIntent().getStringExtra("money");
        setGoodsInfo(list);

        txt_zongji_money.setText("¥"+moneys+"");
        zongMoney=Double.parseDouble(moneys);
        // 购物结束的广播
        IntentFilter filter1 = new IntentFilter(GOUWUINEXIT);
        registerReceiver(endtReceiver, filter1);

        //重新登录的时候推出该页面
        IntentFilter intentFilter = new IntentFilter(SettingActivity.EXITCHANGE);
        registerReceiver(nichengBroadcastReceiver, intentFilter);

    }
    //登陆或退出的广播
    BroadcastReceiver nichengBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    BroadcastReceiver endtReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            CommitOrderActivity.this.finish();
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(endtReceiver);
        unregisterReceiver(nichengBroadcastReceiver);
    }
    @Override
    protected void onStart() {
        super.onStart();
        presenter.onMoney(IsUtilUid.isUid());
    }
    /**
     * 解析上个页面传来的数据
     * @param list
     */
    private void setGoodsInfo(ArrayList<GouWuCheBean> list) {
        if(list!=null){
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getId()+",");
                sb01.append(list.get(i).getCount()+",");
                sb02.append(list.get(i).getPsku_id()+",");
                View viewStore = LayoutInflater.from(getApplicationContext())
                        .inflate(R.layout.include_goodsitem, null);
                TextView txt_goodname = (TextView) viewStore.findViewById(R.id.txt_goodname);
                TextView txt_good_price = (TextView) viewStore.findViewById(R.id.txt_good_price);
                TextView txt_good_num = (TextView) viewStore.findViewById(R.id.txt_good_num);
                txt_goodname.setText(list.get(i).getName());
                txt_good_num.setText(list.get(i).getCount()== 0 ?"*0" :"*"+list.get(i).getCounts());
                txt_good_price.setText(list.get(i).getPrice()== null ?"¥0.00" :"¥"+ MyGongJv.zhuanhua(parseDouble(list.get(i).getPrice())/100));
                LinearLayout.LayoutParams layoutparams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutparams.topMargin=1;
                goods_container.addView(viewStore,layoutparams);
            }
        }
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.quzhifu://去支付
                if(!sb.toString().equals("")){
                    if(sb.length()>0){
                        gwcId=sb.substring(0,sb.length()-1);//购物车Id
                        if(adressId.equals("")){
                            ByAlert.alert("请添加收货地址");
                            return;
                        }
                        taitou=et_taitou.getText().toString().trim();
                        shuihao=et_shuihao.getText().toString().trim();
                        if (type.equals("1")){
                            if(taitou.equals("")){
                                ByAlert.alert("请输入发票抬头");
                                return;
                            }
                        }else if(type.equals("2")){
                            if(taitou.equals("")){
                                ByAlert.alert("请输入发票抬头");
                                return;
                            }
                            if(shuihao.equals("")){
                                ByAlert.alert("请输入发票税号");
                                return;
                            }
                        }
                        String moneyss= txt_zongji_money.getText().toString().substring(1,txt_zongji_money.getText().toString().length());
                        if (Double.parseDouble(moneyss)<=0){
                            uiAlertView = new UIAlertView02(CommitOrderActivity.this, "是否消耗积分", "免额支付", "确定", "取消");
                            uiAlertView.show();
                            uiAlertView.setClicklistener(new UIAlertView02.ClickListenerInterface() {
                                @Override
                                public void doLeft() {
                                    showProgressDialog("正在支付,请稍后", true);
                                    dingDanPresenter.generateOrderTwo(IsUtilUid.sId(),uid,gwcId,adressId+"","0","",order_num.getText().toString(),type,taitou,shuihao);
                                    uiAlertView.dismiss();
                                }
                                @Override
                                public void doRight() {
                                    uiAlertView.dismiss();
                                }
                            });
                        }else{
                            showProgressDialog("提交订单中,请稍后", true);
                            dingDanPresenter.generateOrder(IsUtilUid.sId(),uid,gwcId,adressId+"","0","",order_num.getText().toString(),type,taitou,shuihao);
                        }

                    }
                }else{
                    ByAlert.alert("请添加收货地址");
                }

                break;
            case R.id.choose_address://收货地址
                intent = new Intent(this, AddressListActivity.class);
                intent.putExtra("type","1");
                startActivityForResult(intent, 1);
                break;
            case R.id.close_icon:
                finish();
                break;
            case R.id.order_type:
                pvOptions.show();
                break;
            default:
                break;

        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                    String returnedData = data.getStringExtra("data_return");
                    address_people.setText("收货人:"+data.getStringExtra("name"));
                    adressId=data.getStringExtra("id");
                    address_phone.setText(data.getStringExtra("phone"));
                    address_detail.setText("收货地址:"+data.getStringExtra("addaress"));
                }
                break;
            default:
        }
    }
    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity=handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == UserPresenter.query_address_success) {
                List<MyAddressBean>  list = (List<MyAddressBean>) entity.getData();
                if (list != null) {
                    if (list.size() > 0) {
                        userPresenter.getMoRenAddress(IsUtilUid.sId(),uid);
                    } else {
                      //  ByAlert.alert("没有默认收货地址，建议去添加");
                    }
                } else {
                    //ByAlert.alert("没有默认收货地址，建议去添加");
                }
            }
            if (entity.getEventType() == UserPresenter.query_address_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.moren_address_success) {
                bean = (MyAddressBean) entity.getData();
                address_people.setText("收货人:"+bean.getContactname());
                adressId=bean.getId()+"";
                address_phone.setText(bean.getMobile());
                address_detail.setText("收货地址:"+bean.getProvince()+bean.getCity()+bean.getArea()+bean.getDetailinfo());

            }
            if (entity.getEventType() == UserPresenter.moren_address_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == DingDanPresenter.chuangjian_success) {
                GoPayBean beanss= (GoPayBean) entity.getData();

                Intent intent = new Intent(this, GoPayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", beanss);
                intent.putExtra("time", beanss.getCreate_time());
                intent.putExtra("type","one");//用来标示是首次支付还是重新支付
                intent.putExtras(bundle);
                startActivity(intent);

                Intent intent1 = new Intent(GOUWUSHUXIN);
                sendBroadcast(intent1);

                finish();
            }
            if (entity.getEventType() == DingDanPresenter.chuangjian_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == DingDanPresenter.chuangjian_two_success) {
                finish();
            }
            if (entity.getEventType() == DingDanPresenter.chuangjian_two_fail) {
                ByAlert.alert(entity.getData());
            }

            if (entity.getEventType() == presenter.Yue_success) {
                yeBean = (MoneyShengyuBean) entity.getData();
                jifen(yeBean);

            }
            if (entity.getEventType() == presenter.Yue_fail) {
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    /**
     * 操作积分
     * @param bean
     */
    private void jifen(final MoneyShengyuBean bean){
        score=bean.getScore();
        score_rate=bean.getScore_rate();

        order_jifen.setText(score);
        order_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (Double.parseDouble(score_rate) > zongMoney) {
                        ByAlert.alert("价格太少,积分不能使用");
                        return;
                    }
                    int c = 0;
                    if (!order_num.getText().toString().equals("")) {
                        c = Integer.parseInt(order_num.getText().toString());
                    }
                    if (c>=Integer.parseInt(score)){
                        return;
                    }
                    if (sub(zongMoney,MathUtil.mul(c,Double.parseDouble(score_rate)))<=0){
                        return;
                    }
                    order_num.setText(c + 1 + "");
                    txt_zongji_money.setText("¥"+ sub(zongMoney,MathUtil.mul(c + 1,Double.parseDouble(score_rate))));


                    if (sub(zongMoney, MathUtil.mul(c - 1, Double.parseDouble(score_rate))) < 0) {
                        order_num.setText("0");
                        txt_zongji_money.setText("¥" + zongMoney);
                        return;
                    }
                    if (order_num.getText().toString().equals("0")){
                        txt_zongji_money.setText("¥" + zongMoney);
                    }

                } catch (NumberFormatException e) {
                    order_num.setText("0");
                    txt_zongji_money.setText("¥" + zongMoney);
                }
            }
        });
        order_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int c = 0;
                    if (!order_num.getText().toString().equals("")) {
                        c = Integer.parseInt(order_num.getText().toString());
                    }
                    if (c<=0){
                        return;
                    }
                    order_num.setText(c - 1 + "");
                    txt_zongji_money.setText("¥"+ sub(zongMoney,MathUtil.mul(c - 1,Double.parseDouble(score_rate))));

                    if (order_num.getText().toString().equals("0")){
                        txt_zongji_money.setText("¥" + zongMoney);
                    }

                } catch (NumberFormatException e) {
                    order_num.setText("0");
                    txt_zongji_money.setText("¥" + zongMoney);
                }
            }
        });
        order_num.addTextChangedListener(watcher);
    }
    /**
     *  输入数量时候的监听
     */
    TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //只要编辑框内容有变化就会调用该方法，s为编辑框变化后的内容
            Log.i("onTextChanged", s.toString());

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //编辑框内容变化之前会调用该方法，s为编辑框内容变化之前的内容
            Log.i("beforeTextChanged", s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            //编辑框内容变化之后会调用该方法，s为编辑框内容变化后的内容
            Log.i("afterTextChanged", s.toString());
            if(!s.toString().equals("")){
                int shuru = 0;
                if (!s.toString().equals("")) {
                    shuru = Integer.parseInt(s.toString());
                }
                if(shuru>Integer.parseInt(score)){
                    order_num.setText("0");
                    ByAlert.alert("没有这么多积分");
                    return;
                }

                if (order_num.getText().toString().equals("0")){
                    txt_zongji_money.setText("¥" + zongMoney);
                }
                try {
                    if (sub(zongMoney, MathUtil.mul(shuru, Double.parseDouble(score_rate))) < 0) {
                        order_num.setText("0");
                        ByAlert.alert("该订单最多能使用" + MathUtil.div(zongMoney, Double.parseDouble(score_rate), 2) + "积分");
                        return;
                    }
                } catch (Exception e) {
                    order_num.setText("0");
                }

                txt_zongji_money.setText("¥"+ sub(zongMoney,MathUtil.mul(shuru,Double.parseDouble(score_rate))));
            }
        }
    };
    private ArrayList<String> options1Items = new ArrayList<>();
    /**
     * 选择发票抬头
     */
    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);
                tv_type.setText(tx);
                if (options1==0){
                    type="";
                    xianshi();
                }else if (options1==1){
                    type="1";
                    xianshi();
                    order_taitou.setVisibility(View.VISIBLE);
                }else if (options1==2){
                    type="2";
                    xianshi();
                    order_taitou.setVisibility(View.VISIBLE);
                    order_shuihao.setVisibility(View.VISIBLE);
                }
            }
        })
                .setTitleText("发票抬头类型")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptions.setPicker(options1Items);//1级选择器
    }
    private void getOptionData() {
        //选项1
        options1Items.add("无");
        options1Items.add("个人");
        options1Items.add("企业");
    }
    private void xianshi() {
        order_taitou.setVisibility(View.GONE);
        order_shuihao.setVisibility(View.GONE);
    }
}
